package org.railage.client.gui.dialogs;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;

import org.apache.log4j.Logger;
import org.railage.client.Client;
import org.railage.client.gui.main.GUI;
import org.railage.client.gui.main.MainFrame;
import org.railage.common.dto.UserDTO;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Color;
import java.io.IOException;
import java.net.UnknownHostException;

public class AuthDialog extends JDialog {

	private static final long serialVersionUID = 724426235625855206L;

	private static final Logger log = Logger.getLogger(AuthDialog.class);

	private final JPanel contentPanel = new JPanel();
	private JTextField loginField;
	private JTextField passwordField;
	private JLabel infoLabel;

	/**
	 * Create the dialog.
	 */
	public AuthDialog() {
		setAlwaysOnTop(true);
		setTitle(GUI.PROGRAM_NAME + " - Authentication");
		setIconImage(Toolkit.getDefaultToolkit().getImage(
				getClass().getClassLoader().getResource(GUI.ICON_PATH)));
		setSize(430, 264);
		setResizable(false);
		setLocationRelativeTo(null);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);

		JLabel lblPleaseEnterYour = new JLabel(
				"Please, enter your username and password below and press Login:");
		lblPleaseEnterYour.setBounds(10, 24, 394, 35);
		contentPanel.add(lblPleaseEnterYour);

		JLabel lblUsername = new JLabel("Username");
		lblUsername.setBounds(106, 70, 82, 14);
		contentPanel.add(lblUsername);

		loginField = new JTextField();
		loginField.setBounds(198, 67, 118, 20);
		contentPanel.add(loginField);
		loginField.setColumns(10);

		JLabel lblPassword = new JLabel("Password");
		lblPassword.setBounds(106, 101, 82, 14);
		contentPanel.add(lblPassword);

		passwordField = new JPasswordField();
		passwordField.setColumns(10);
		passwordField.setBounds(198, 98, 118, 20);
		contentPanel.add(passwordField);

		// String with authentication info
		infoLabel = new JLabel();
		infoLabel.setForeground(Color.RED);
		infoLabel.setBounds(20, 151, 178, 14);

		contentPanel.add(infoLabel);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton loginButton = new JButton("Login");
				loginButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						login();
					}
				});
				loginButton.setActionCommand("OK");
				buttonPane.add(loginButton);
				getRootPane().setDefaultButton(loginButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						GUI.exit();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}

		// default close operation and visibility
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				GUI.exit();
			}
		});
		setVisible(true);
	}

	private void login() {
		try {
			if (!Client.getInstance().isConnected()) {
				Client.getInstance().connect();
			}
			String[] userData = new String[] { loginField.getText(),
					passwordField.getText() };
			UserDTO user = (UserDTO) Client.getInstance().callMethod(
					"authenticate", userData);
			if (user == null) {
				String msg = "Incorrect login or password";
				infoLabel.setText(msg);
				log.warn(msg);
			} else {
				log.info("Authenticated successfully!");
				Client.getInstance().setCurrentUser(user);
				setVisible(false);
				dispose();
				new MainFrame();
			}
		} catch (UnknownHostException e) {
			String msg = "Cannot determine IP address of server. Check setting.ini";
			infoLabel.setText(msg);
			log.error(msg, e);
		} catch (IOException e) {
			String msg = "Cannot connect to server";
			infoLabel.setText(msg);
			log.error(msg, e);
		}
	}
}
